package com.example.demo.common;

import cn.hutool.v7.core.collection.CollUtil;
import cn.hutool.v7.core.text.StrUtil;
import org.noear.snack4.ONode;
import org.noear.snack4.codec.EncodeContext;
import org.noear.snack4.codec.ObjectPatternEncoder;

import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

/**
 * @author airhead
 */
public class ModelEncoder<T extends Model<?>> implements ObjectPatternEncoder<T> {

  /** 对 Model 和 Record 的字段名进行转换的函数。例如转成驼峰形式对 oracle 支持更友好 */
  protected static Function<String, String> fieldNameConverter = StrUtil::toCamelCase;

  @Override
  public ONode encode(EncodeContext ctx, T value, ONode node) {
    if (value == null) {
      return node;
    }

    return encode(node, CPI.getAttrs(value));
  }

  @Override
  public boolean canEncode(Object value) {
    return value instanceof Model;
  }

  protected ONode encode(ONode node, Map<String, Object> map) {
    if (CollUtil.isEmpty(map)) {
      return node;
    }

    Map<String, Object> newMap = new HashMap<>(map.size());
    for (Map.Entry<String, Object> entry : map.entrySet()) {
      String fieldName = entry.getKey();
      Object value = entry.getValue();
      String attrName = fieldName;
      if (fieldNameConverter != null) {
        attrName = fieldNameConverter.apply(fieldName);
      }
      newMap.put(attrName, value);
    }

    node.fill(newMap);

    return node;
  }
}
